package com.ruoyi.business.appuser.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.BusOrder;
import com.ruoyi.system.domain.BusSearchRecord;
import com.ruoyi.system.domain.vo.BusOrderVo;
import com.ruoyi.system.mapper.BusOrderMapper;
import com.ruoyi.system.mapper.BusSearchRecordMapper;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.IBusOrderService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping(value = "api")
public class ApiController {

    //企查查接口查询
    private  static final String url=" https://api.qichacha.com/FuzzySearch/GetList";

    private static final String appkey="bff2a979726c4f4aace869c33259a2f0";
    private static final String secretKey="AFEE23BFFE0AB1F99D9CC535A89D713A";

    @Resource
    private WxMaService wxMaService;

    @Resource
    private BusOrderMapper orderMapper;

    @Resource
    private ISysConfigService configService;

    @Resource
    private WxPayService wxService;

    @Resource
    private BusSearchRecordMapper searchRecordMapper;

    //企业查询
    @GetMapping(value = "select")
    public AjaxResult select(String searchKey) throws IOException {
        System.err.println("jinru"+searchKey);
//        BusSearchRecord record=new BusSearchRecord();
//        record.setSearchKey(searchKey);
//        record.setCreateDate(DateUtil.formatDateTime(new DateTime()));
//        searchRecordMapper.insert(record);
//        Map<String, String>pd=new HashMap<>();
//        String timespan=String.valueOf(System.currentTimeMillis()/1000);
//        pd.put("Token",getToken(timespan));
//        pd.put("Timespan",timespan);
//        String s = HttpUtils.sendGetHeaders(url + "?key=" + appkey + "&searchKey=" + searchKey, pd);
        return null;
//        return AjaxResult.success("成功",s);
    }

    @ApiOperation("微信登录")
    @GetMapping(value = "wxLogin")
    public AjaxResult wxLogin(String code) throws WxErrorException {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        return AjaxResult.success(sessionInfo);
    }

    @ApiOperation("查询支付配置信息")
    @GetMapping(value = "selectPayConfig")
    public AjaxResult selectPayConfig(String key){
        String s = configService.selectConfigByKey(key);
        return AjaxResult.success("成功",s);
    }

    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param request 统一下单请求参数
     * @param <T>     请使用{@link com.github.binarywang.wxpay.bean.order}包下的类
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @ApiOperation(value = "统一下单，并组装所需支付参数")
    @PostMapping("/createOrder")
    public <T> T createOrder(@RequestBody WxPayUnifiedOrderRequest request) throws WxPayException {
        request.setNotifyUrl("https://www.lingxiaohan.vip/api/notify/order");
        return this.wxService.createOrder(request);
    }

    @ApiOperation(value = "支付回调通知处理")
    @PostMapping("/notify/order")
    public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
        System.err.println("进入回调地址了");
        final WxPayOrderNotifyResult notifyResult = this.wxService.parseOrderNotifyResult(xmlData);
        // TODO 根据自己业务场景需要构造返回对象
        orderMapper.update(null,Wrappers.<BusOrder>lambdaUpdate()
                .set(BusOrder::getState,1)
                .eq(BusOrder::getOrderNo,notifyResult.getOutTradeNo()));
        return WxPayNotifyResponse.success("成功");
    }
    @ApiOperation("下单接口")
    @PostMapping(value = "addOrder")
    public AjaxResult addOrder(@RequestBody BusOrder busOrder,@RequestHeader("token")String openid) throws WxPayException {
        String payPrice = configService.selectConfigByKey("pay_price");
        BigDecimal bigPrice = new BigDecimal(payPrice).multiply(new BigDecimal(100));
        //查看下单金额
        busOrder.setCreateDate(DateUtil.formatDateTime(new DateTime()));
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        String randomNumeric = RandomStringUtils.randomNumeric(4);
        busOrder.setOrderNo(localDate+randomNumeric);
        busOrder.setOpenId(openid);
        busOrder.setPrice(new BigDecimal(payPrice));
        orderMapper.insert(busOrder);
        //唤起支付
        WxPayUnifiedOrderRequest request=new WxPayUnifiedOrderRequest();
        request.setNotifyUrl("https://www.lingxiaohan.vip/api/notify/order");
        request.setVersion("1.0.0");
        request.setBody("虚拟商品");
        request.setOpenid(openid);
        request.setOutTradeNo(busOrder.getOrderNo());
        request.setSpbillCreateIp("127.0.0.1");
        request.setTradeType("JSAPI");
        request.setTotalFee(bigPrice.intValue());
        return AjaxResult.success("下单成功",this.wxService.createOrder(request));
    }

    @ApiOperation("查看订单列表")
    @GetMapping(value = "selectOrder")
    public AjaxResult selectOrder(@RequestHeader("token")String openid,String state){
        List<BusOrder> busOrders = orderMapper.selectList(Wrappers.<BusOrder>lambdaQuery()
                .eq(BusOrder::getOpenId, openid)
                .eq(StringUtils.isNotBlank(state)&& !state.equals("0"),BusOrder::getState,state)
                .orderByDesc(BusOrder::getCreateDate));
        return AjaxResult.success(busOrders);
    }

    public static String getToken(String timespan){
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String hash = md5.digestHex(appkey + timespan + secretKey);
        return hash.toUpperCase();
    }

    public static void main(String[] args) {

//        System.out.println(localDate+randomNumeric);
    }

}
